<template>
    <div>
        <div style="width: 100%;display: flex;flex-wrap: wrap;align-content: flex-start;">
            <div style="
                font-size: 28px;
                color: #8c939d;
                width: 100px;
                height: 100px;
                line-height: 100px;
                text-align: center;
                border: 1px dashed #d9d9d9;
                cursor: pointer;
                margin-top: 10px;
                margin-right: 10px;" @click="editCropper()" v-if="dialogType != 'see'">
                <i class="el-icon-plus"></i>
            </div>
            <div v-for="(item,index) in photos" :key="item"
                style="position: relative;margin-right: 10px;margin-top: 10px;width: 100px;height: 100px;">
                <img :src="baseUrl + item" style="width: 100%; height: 100%; cursor: pointer;"
                    @click="previewimg(item)" />
                <img src="../../assets/images/cuo.png" alt=""
                    style="z-index: 9;position: absolute;right: -5px;top: -5px;width: 16px;height: 16px;cursor: pointer;"
                    @click="deleteimg(item,index)" v-if="dialogType != 'see'">
            </div>
        </div>
        <div class="el-upload__tip" slot="tip">
            请上传
            <template v-if="fileDimensions"> 尺寸为 <b style="color: #f56c6c">{{ fileDimensions }}</b> </template>
            <template v-if="fileSize"> ,大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
            <template v-if="fileType"> ,格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
            的文件
        </div>
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @opened="modalOpened"
            @close="closeDialog">
            <el-row>
                <el-col :xs="24" :md="12" :style="{height: '350px'}">
                    <vue-cropper ref="cropper" :img="options.img" :info="true" :autoCrop="options.autoCrop"
                        :autoCropWidth="options.autoCropWidth" :autoCropHeight="options.autoCropHeight"
                        :fixedBox="options.fixedBox" @realTime="realTime" v-if="visible" :canScale="options.canScale"
                        :original="options.original" :canMoveBox="options.canMoveBox" :maxImgSize="350" />
                </el-col>
                <el-col :xs="24" :md="12" :style="{height: '350px'}">
                    <div class="avatar-upload-preview">
                        <img :src="previews.url" :style="previews.img" />
                    </div>
                </el-col>
            </el-row>
            <br />
            <el-row>
                <el-col :lg="2" :md="2">
                    <el-upload action="#" :http-request="requestUpload" :show-file-list="false"
                        :before-upload="beforeUpload">
                        <el-button size="small">
                            选择
                            <i class="el-icon-upload el-icon--right"></i>
                        </el-button>
                    </el-upload>
                </el-col>
                <el-col :lg="{span: 1, offset: 2}" :md="2">
                    <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :md="2">
                    <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :md="2">
                    <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
                </el-col>
                <el-col :lg="{span: 1, offset: 1}" :md="2">
                    <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
                </el-col>
                <el-col :lg="{span: 2, offset: 6}" :md="2">
                    <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
        </el-dialog>
    </div>
</template>

<script>
    import store from "@/store";
    import { VueCropper } from "vue-cropper";
    import { uploadAvatar, uploadphoto } from "@/api/system/user";

    export default {
        components: { VueCropper },
        props: {
            user: {
                type: Object
            },
            limit: {
                type: Number,
                default: 10000
            },
            value: {
                type: String,
                default: ''
            },
            dialogType: {
                type: String,
                default: 'edit'
            },
            // 大小限制(MB)
            fileSize: {
                type: Number,
                default: 5,
            },
            // 文件类型, 例如['png', 'jpg', 'jpeg']
            fileType: {
                type: Array,
                default: () => ["png", "jpg", "jpeg"],
            },
            // 尺寸限制(334*180)
            fileDimensions: {
                type: String,
                default: "180*180",
            },
        },
        data() {
            return {
                baseUrl: process.env.VUE_APP_BASE_API,
                // 是否显示弹出层
                open: false,
                // 是否显示cropper
                visible: false,
                // 弹出层标题
                title: "裁剪图片",
                options: {
                    img: store.getters.avatar, //裁剪图片的地址
                    autoCrop: true, // 是否默认生成截图框
                    autoCropWidth: 200, // 默认生成截图框宽度
                    autoCropHeight: 200, // 默认生成截图框高度
                    fixedBox: false, // 固定截图框大小 不允许改变
                    canMove: true, //指定是否允许移动裁剪框
                    canMoveBox: true,
                    original: true,
                    canScale: false,
                },
                previews: {},
                photos: [],
                dialogVisible: false,
                dialogImageUrl: ''
            };
        },
        watch: {
            value: {
                handler(val) {
                    console.log(val, '****')
                    if (val) {
                        // 首先将值转为数组
                        this.photos = Array.isArray(val) ? val : this.value.split(',');
                    } else {
                        this.photos = []
                    }
                },
                deep: true,
                immediate: true
            }
        },
        mounted() {

        },
        methods: {
            // 编辑头像
            editCropper(item) {
                if (item) {
                    this.options.img = this.baseUrl + item
                } else {
                    this.options.img = ''
                }
                this.open = true;
            },
            // 打开弹出层结束时的回调
            modalOpened() {
                this.visible = true;
            },
            // 覆盖默认的上传行为
            requestUpload() {
            },
            // 向左旋转
            rotateLeft() {
                this.$refs.cropper.rotateLeft();
            },
            // 向右旋转
            rotateRight() {
                this.$refs.cropper.rotateRight();
            },
            // 图片缩放
            changeScale(num) {
                num = num || 1;
                this.$refs.cropper.changeScale(num);
            },
            // 上传预处理
            beforeUpload(file) {
                console.log(file, '上传预处理')
                if (file.type.indexOf("image/") == -1) {
                    this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
                } else {
                    if (this.fileSize) {
                        const isLt = file.size / 1024 / 1024 < this.fileSize;
                        if (!isLt) {
                            this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
                            return false;
                        }
                    }
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => {
                        this.options.img = reader.result;
                    };
                }
            },
            // 上传图片
            uploadImg() {
                if (this.limit == 1) {
                    if (this.photos.length == this.limit) {
                        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个`)
                        return
                    }
                }
                this.$refs.cropper.getCropBlob(data => {
                    let formData = new FormData();
                    formData.append("file", data, this.options.filename);
                    uploadphoto(formData).then(response => {
                        this.open = false;
                        this.options.img = process.env.VUE_APP_BASE_API + response.fileName;
                        this.photos.push(response.fileName)
                        this.$emit('getImg', this.photos);
                        this.visible = false;
                    });
                });
            },
            // 实时预览
            realTime(data) {
                this.previews = data;
            },
            // 关闭窗口
            closeDialog() {
                this.options.img = ''
                this.visible = false;
            },
            // 删除图片
            deleteimg(item, index) {
                this.photos.splice(index, 1)
                this.$emit('getImg', this.photos);
            },
            // 预览
            previewimg(item) {
                console.log(item, '*--------')
                this.dialogImageUrl = this.baseUrl + item;
                this.dialogVisible = true;
            }
        }
    };
</script>
<style scoped lang="scss">
    .user-info-head {
        position: relative;
        display: inline-block;
        height: 120px;
    }

    .user-info-head:hover:after {
        content: '+';
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        color: #eee;
        background: rgba(0, 0, 0, 0.5);
        font-size: 24px;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        cursor: pointer;
        line-height: 110px;
        border-radius: 50%;
    }
</style>